package com.kuangstudy.controller.session;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.kuangstudy.entity.User;
import com.kuangstudy.service.UserService;
import com.kuangstudy.vo.R;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;

/**
 * @author 飞哥
 * @Title: 学相伴出品
 * @Description: 我们有一个学习网站：https://www.kuangstudy.com
 * @date 2021/5/23 10:41
 */
@RestController
@Slf4j
public class LoginController {

    @Autowired
    private UserService userService;

    /**
     * 1: 用户登录逻辑
     *
     * @param nickname
     * @param password
     * @param session
     * @return
     */
    @PostMapping("/user/login")
    public R userlogin(String nickname, String password, @ApiIgnore  HttpSession session) {
        log.info("当前登录得用户是：{},{}", nickname, password);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<User>();
        queryWrapper.eq(User::getNickname, nickname);
        User user = userService.getOne(queryWrapper);
        if (user != null) {
            if (user.getPassword().equals(password)) {
                session.setAttribute(session.getId(), user);
                return R.ok().message("登录成功!");
            }
            return R.error().code(401).message("输入得用户名或密码有误!");
        }
        return R.error().code(401).message("用户不存在!");
    }


    /**
     * 获取用户session信息
     *
     * @param session
     * @return
     */
    @PostMapping("/user/session")
    public R usesesion( @ApiIgnore HttpSession session) {
        log.info("当前用户得session信息是：{}", session.getId());
        User user = (User) session.getAttribute(session.getId());
        return R.ok().data("user", user);
    }


    /**
     * 用户退出
     *
     * @param session
     * @return
     */
    @PostMapping("/user/logout")
    public R logout( @ApiIgnore HttpSession session) {
        log.info("当前注销得用户得session信息是：{}", session.getId());
        session.invalidate();
        return R.ok();
    }
}
